# -*- coding: utf_8 -*-
# @Time : 2021/8/12 0012 15:24
# @Author : lyw
# @Remark : 门禁出入记录
import time

from mxsoftpy import TreeDB

from index import mini_cache
from utils.public.janitor_serial import Serial


class RecordDB(TreeDB):
    def query_record(self, export=None, **kwargs):
        # print(kwargs)

        total, record_key = self.open("Janitor", "record", file="IOT").filter(**kwargs)
        if export is not None:
            # 获取序号
            iter_obj = iter([i + 1 for i in range(len(record_key))])
        else:
            ser = Serial(total, kwargs["page_size"], kwargs["page_index"])
            iter_obj = iter(ser)

        res_list = []
        for i in record_key:
            value = self.open("Janitor", "record\\%s" % i, file="IOT").items()
            door_id = value.pop("door_id")
            try:
                cache_dict = self.get_door()
                # 获取 操作
                value["motion"] = cache_dict[door_id]["model"][value["motion"]]
                # 获取门禁名称
                value["door_name"] = cache_dict[door_id]["name"]
            except KeyError:
                value["motion"] = ""
                value["door_name"] = ""
            personnel_data = self.get_personnel(value.pop("pers_id"))
            value["personnel"] = personnel_data["name"]
            value["fingerprint"] = personnel_data["fingerprint"]
            value["id"] = next(iter_obj)
            value["create_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value["create_time"]))
            value["desc"] = ""
            res_list.append(value)

        return total, res_list

    def get_personnel(self, peas_id):
        return self.open("Janitor", "personnel\\%s" % peas_id, file="IOT").items(["name", "fingerprint"])

    def get_door(self):
        """获取门禁信息"""
        res_dict = mini_cache.get("JANITOR_DOOR")
        if not res_dict:
            sub_key_list = self.open("Janitor", "door", file="IOT").sub_keys()
            res_dict = {}
            for sub_key_str in sub_key_list:
                door_data = self.open("Janitor", "door\\%s" % sub_key_str, file="IOT").items(
                    prop_list=["label", "model_id"])
                res_dict[sub_key_str] = {"label": door_data["label"], "model": self.get_model(door_data["model_id"])}
            mini_cache.set("JANITOR_DOOR", res_dict, 60 * 60 * 24)
        return res_dict

    def get_model(self, model_id):
        """
        获取模板
        @param model_id:
        @return:
        """
        return self.open("Janitor", "data_origin_conf\\%s\\motion" % model_id, file="IOT").items()

    def query_personnel(self, **kwargs):
        res_dict = {}
        count, personnel_key = self.open("Janitor", "personnel", file="IOT").filter(**kwargs)
        if count <= 490:
            return personnel_key
        for i in personnel_key:
            personnel_data = self.open("Janitor", "personnel\\%s" % i, file="IOT").items()
            if res_dict.get(personnel_data["door_id"]):
                if len(res_dict[personnel_data["door_id"]]) >= 20:
                    continue
                else:
                    res_dict[personnel_data["door_id"]].append(i)
            else:
                res_dict[personnel_data["door_id"]] = [i]
        res_list = []
        for key, value in res_dict.items():
            res_list.extend(value)
        return res_list

    def query_door(self, **kwargs):
        return self.open("Janitor", "door", file="IOT").filter(**kwargs)[1]
